package com.example.server.controller;

import com.example.server.entity.ChatMessage;
import com.example.server.util.ContentProcessor;
import com.example.server.util.SignatureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/content")
public class ContentController {

    private final WebClient webClient;
    private final SignatureUtil signatureUtil;

    @Autowired
    public ContentController(WebClient webClient, SignatureUtil signatureUtil) {
        this.webClient = webClient;
        this.signatureUtil = signatureUtil;
    }

    @PostMapping("/send")
    public Mono<ResponseEntity<Map<String, Object>>> sendMessage(@RequestBody ChatMessage message) {
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("requestId", UUID.randomUUID().toString());

        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        queryParams.forEach(multiValueMap::add);

        System.out.println("Received message from frontend:");
        System.out.println("Content: " + message.getContent());

        return webClient.post()
                .uri(uriBuilder -> uriBuilder.path("/vivogpt/completions")
                        .queryParams(multiValueMap)
                        .build())
                .headers(headers -> headers.setAll(signatureUtil.generateAuthHeaders("POST", "/vivogpt/completions", queryParams)))
                .bodyValue(buildRequestBody(message))
                .retrieve()
                .bodyToMono(String.class)
                .map(body -> {
                    System.out.println("AIGC Feedback:");
                    System.out.println(body); // Print the feedback

                    // Process the content
                    String processedContent = ContentProcessor.processContent(message.getContent(), body);

                    Map<String, Object> response = new HashMap<>();
                    response.put("original", message.getContent());
                    response.put("processed", processedContent);

                    return ResponseEntity.ok().body(response);
                })
                .onErrorResume(e -> {
                    e.printStackTrace();
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("error", "Error processing your request: " + e.getMessage());
                    return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse));
                });
    }

    @PostMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestBody Map<String, String> request) {
        String content = request.get("content");
        try {
            File tempFile = File.createTempFile("processed", ".txt");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
                writer.write(content);
            }

            InputStreamResource resource = new InputStreamResource(new FileInputStream(tempFile));

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=processed.txt")
                    .body(resource);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    private String buildRequestBody(ChatMessage message) {
        return String.format("{\"prompt\": \"%s\", \"model\": \"vivo-BlueLM-TB\", \"sessionId\": \"%s\"}",
                message.getContent(),
                message.getSessionId());
    }
}
